package com.eningqu.aipen.demo;

import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.os.PowerManager;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.LogUtils;
import com.eningqu.aipen.demo.common.Const;
import com.eningqu.aipen.sdk.IPenCtrl;
import com.eningqu.aipen.sdk.NQPenSDK;
import com.eningqu.aipen.sdk.bean.device.NQDeviceBase;
import com.eningqu.aipen.sdk.comm.ConnectState;
import com.eningqu.aipen.sdk.comm.ScanListener;
import com.eningqu.aipen.sdk.listener.InitListener;
import com.eningqu.aipen.sdk.listener.PenConnectListener;
import com.eningqu.aipen.sdk.listener.PenDotListener;
import com.eningqu.aipen.sdk.listener.PenMsgListener;
import com.eningqu.aipen.sdk.listener.PenOfflineDataListener;

/**
* @Author: Qiu.Li
* @Create Date: 2021/2/3 20:41
* @Description: 智能笔SDK管理单例，对sdk进行二次封装
* @Email: lq@eningqu.com
*/
public class PenCtrlSdkManager implements IPenCtrl {

    private static PenCtrlSdkManager instance;
    private Context mContext;
    PowerManager.WakeLock mWakeLock;
    /**
     * 连接回调
     */
    private PenConnectListener mConnectListener;
    /**
     * 扫描回调
     */
    private ScanListener mScanListener;
    /**
     * 当前连接的设备
     */
    private NQDeviceBase mCurNQDev;
    /**
     * 默认的连接方式
     */
    NQPenSDK.CONN_TYPE mConnType = NQPenSDK.CONN_TYPE.USB;

    /**
     * 连接状态
     */
    int mConnState = ConnectState.CONN_STATE_CLOSED;

    /**
     * 页面尺寸列表
     */
//    List<PageSize> mPageList = new ArrayList<>();

    public static PenCtrlSdkManager getInstance() {

        if (null == instance) {
            synchronized (PenCtrlSdkManager.class) {

                if (null == instance) {
                    instance = new PenCtrlSdkManager();
                }
            }
        }

        return instance;
    }

    /**
     * SDK初始化
     *
     * @param context
     */
    public void init(@NonNull Context context, NQPenSDK.CONN_TYPE type) {
        mContext = context;
        mConnType = type;
        //初始化
        NQPenSDK.getInstance().init(context, type, initListener);
        //初始化页面尺寸
        setDefaultPageSize();
        //获取电源锁，保持CPU运转，保持屏幕常亮(亮度低)
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, PenCtrlSdkManager.class.getName());

        if(null!=mWakeLock){
            mWakeLock.acquire();
        }

        //设置远程解析
        NQPenSDK.getInstance().setRemoteParse(false);
    }

    /**
     * 使用sdk资源
     * 断开智能笔时调用
     */
    public void release() {
        setCurNQDev(null);
        //释放SDK资源
        NQPenSDK.getInstance().release();
        //释放电源锁
        if(null!=mWakeLock){
            mWakeLock.release();
        }
    }

    /**
     *
     * @return 当前连接的设备
     */
    public NQDeviceBase getCurNQDev() {
        return mCurNQDev;
    }

    public void setCurNQDev(NQDeviceBase curNQDev) {
        this.mCurNQDev = curNQDev;
    }

    /**
     * SDK初始化回调
     */
    InitListener initListener = new InitListener() {
        @Override
        public void success(NQPenSDK.CONN_TYPE conn_type) {
            LogUtils.d("init sdk success...");
            //设置扫描连接监听
            NQPenSDK.getInstance().setPenConnectListener(connectListener);
            //查找设备
            startScanDevice();
        }

        @Override
        public void failure(int error, String message) {
            LogUtils.e("init sdk failure error="+error+", message="+message);
        }
    };

    /**
     * 设置默认码点页面
     */
    public void setDefaultPageSize(){
        //设置bookNum对应的页面尺寸(铺码的纸张宽高，单位:毫米)和页码范围
        //此处以设置A4 bookNum=1和A5 bookNum=2为例
        NQPenSDK.getInstance().addPageSizeByPaperSize(165, 235, Const.PageSizeType.BOOK_NUM_A4, 0, 30000);
//        NQPenSDK.getInstance().addPageSizeByPaperSize(379, 269, Const.PageSizeType.BOOK_NUM_A6, 301, 388);
//        NQPenSDK.getInstance().addPageSizeByPaperSize(219, 299, Const.PageSizeType.BOOK_NUM_A7, 389, 879);
//        NQPenSDK.getInstance().addPageSizeByPaperSize(423, 300, Const.PageSizeType.BOOK_NUM_A8, 880, 902);
//        NQPenSDK.getInstance().addPageSizeByPaperSize(183, 269, Const.PageSizeType.BOOK_NUM_A9, 902, 1022);
//        NQPenSDK.getInstance().addPageSizeByPaperSize(210, 297, Const.PageSizeType.BOOK_NUM_A10, 1023, 20000);
    }

    /**
     * 设置0-300页适配A4纸张
     */
    public void setPageSizeForA4(){
        NQPenSDK.getInstance().addPageSizeByPaperSize(210, 297, Const.PageSizeType.BOOK_NUM_A4, 0, 300);
    }

    /**
     * 设置0-300页适配A5纸张
     */
    public void setPageSizeForA5(){
        NQPenSDK.getInstance().addPageSizeByPaperSize(148, 211, Const.PageSizeType.BOOK_NUM_A4, 0, 300);
    }

    public NQPenSDK.CONN_TYPE getConnType(){
        return NQPenSDK.getInstance().getConnType();
    }

    public int getConnState(){
        return this.mConnState;
    }

    /**
     * 扫描连接监听
     */
    PenConnectListener connectListener = new PenConnectListener() {
        /**
         * 连接状态
         * @param state
         */
        @Override
        public void onConnectState(int state) {
//            LogUtils.d("onConnectState state="+state);
            mConnState = state;
            if (null != mConnectListener) {
                mConnectListener.onConnectState(state);
            }

            //当前状态是已连接
            if(state==ConnectState.CONN_STATE_CONNECTED){
                mContext.sendBroadcast(new Intent(Const.Broadcast.ACTION_CONNECTED));
            }
        }

        /**
         * usb插入监听
         * @param usbDevice
         */
        @Override
        public void onUsbDeviceAttached(UsbDevice usbDevice) {
            Intent intent = new Intent(Const.Broadcast.ACTION_USB_DEVICE_ATTACHED);
            intent.putExtra("device", usbDevice);
            if (null != mContext) {
                mContext.sendBroadcast(intent);
            }

            if(null!=mConnectListener){
                mConnectListener.onUsbDeviceAttached(usbDevice);
            }
        }

        /**
         * usb拔出监听
         * @param usbDevice
         */
        @Override
        public void onUsbDeviceDetached(UsbDevice usbDevice) {
            Intent intent = new Intent(Const.Broadcast.ACTION_USB_DEVICE_DETACHED);
            intent.putExtra("device", usbDevice);
            if (null != mContext) {
                mContext.sendBroadcast(intent);
            }

            if(null!=mConnectListener){
                mConnectListener.onUsbDeviceDetached(usbDevice);
            }
        }


        /**
         * 扫描异常
         * @param error
         * @param message
         */
        @Override
        public void onReceiveException(int error, String message) {
            LogUtils.e("receiveException error=" + error + ", message=" + message);

            Intent intent = new Intent(Const.Broadcast.ACTION_FIND_ERROR);
            intent.putExtra("error", error);
            intent.putExtra("message", message);
            if (null != mContext) {
                mContext.sendBroadcast(intent);
            }

            if(null!=mScanListener){
                mScanListener.onReceiveException(error, message);
            }
            if(null!=mConnectListener){
                mConnectListener.onReceiveException(error, message);
            }
        }

    };

    /**
     * 搜索设备
     *
     * @return
     */
    @Override
    public int startScanDevice() {
        return NQPenSDK.getInstance().startScanDevice();
    }

    /**
     * 停止搜索
     */
    @Override
    public void stopScan() {
        NQPenSDK.getInstance().stopScan();
    }

    /**
     * 连接设备
     *
     * @param deviceBase
     */
    @Override
    public void connect(NQDeviceBase deviceBase) {
        NQPenSDK.getInstance().connect(deviceBase);
    }

    /**
     * 断开连接
     */
    @Override
    public void disconnect() {
        NQPenSDK.getInstance().disconnect();
    }

    /**
     * 返回当前连接的设备
     * @return
     */
    @Override
    public NQDeviceBase getConnectedDevice() {
        return NQPenSDK.getInstance().getConnectedDevice();
    }

    /**
     * 获取固件版本
     */
    @Override
    public void requestFirWareVersion() {
        NQPenSDK.getInstance().requestFirWareVersion();
    }

    /**
     * 获取sdk版本
     */
    @Override
    public String requestSdkVersion() {
        return NQPenSDK.getInstance().requestSdkVersion();
    }

    @Override
    public String requestMcuVersion() {
        return NQPenSDK.getInstance().requestMcuVersion();
    }

    /**
     * 获取电量信息
     */
    @Override
    public void requestBatInfo() {
        NQPenSDK.getInstance().requestBatInfo();
    }

    /**
     * 获取离线数据量
     */
    @Override
    public void requestOfflineDataLength() {
        NQPenSDK.getInstance().requestOfflineDataLength();
    }

    /**
     * 获取离线数据
     */
    @Override
    public void requestOfflineDataWithRange(int i, int i1) {
        NQPenSDK.getInstance().requestOfflineDataWithRange(i,i1);
    }

    /**
     * 删除离线数据
     */
    @Override
    public void requestDeleteOfflineData() {
        NQPenSDK.getInstance().requestDeleteOfflineData();
    }

    /**
     * 修改蓝牙设备名称
     * @param name
     */
    @Override
    public void editBleDeviceName(String name) {
        NQPenSDK.getInstance().editBleDeviceName(name);
    }

    @Override
    public void requestBleDeviceVersion() {

    }

    /**
     * 获取序列号
     */
    @Override
    public void readDeviceSerialNumber() {
        NQPenSDK.getInstance().readDeviceSerialNumber();
    }

    /**
     * 设置蓝牙搜索名称过滤关键字
     * @param value 格式："name1|name2"
     */
    public void setBtScannerFilterValue(String value){
        NQPenSDK.getInstance().setBtScannerFilterValue(value);
    }

    /**
     * 设置实时书写数据监听
     *
     * @param listener
     */
    @Override
    public void setDotListener(PenDotListener listener) {
        NQPenSDK.getInstance().setDotListener(listener);
    }

    @Override
    public void setPenOfflineDataListener(PenOfflineDataListener listener) {
        NQPenSDK.getInstance().setPenOfflineDataListener(listener);
    }

    @Override
    public void setPenConnectListener(PenConnectListener listener) {
        //设置扫描连接监听
        NQPenSDK.getInstance().setPenConnectListener(listener);
    }

    /**
     * 设置连接监听
     *
     * @param connectListener
     */
    public void setConnectListener(PenConnectListener connectListener) {
        this.mConnectListener = connectListener;
    }

    public void setScanListener(ScanListener scanListener){
        this.mScanListener = scanListener;
        NQPenSDK.getInstance().setScanListener(mScanListener);
    }

    public void setPenMsgListener(PenMsgListener penMsgListener){
        NQPenSDK.getInstance().setPenMsgListener(penMsgListener);
    }



    @Override
    public void getFlashUsedAmount() {

    }

    @Override
    public void getFlashCapacity() {

    }



}
